package com.ncloud.resman.busi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.JsonUtil;
import com.ncloud.common.utils.PageHelperUtils;
import com.ncloud.resman.constant.ResConstant;
import com.ncloud.resman.entity.*;
import com.ncloud.resman.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by shiqiang on 2017/8/15.
 */
@Service
public class DeviceLocationBusi {
    @Autowired
    private DeviceLocationService deviceLocationService;
    @Autowired
    private DeviceBaseService deviceBaseService;
    @Autowired
    private DeviceServerService deviceServerService;
    @Autowired
    private DeviceSwitchService deviceSwitchService;
    @Autowired
    private DeviceIpService deviceIpService;
    @Autowired
    private DeviceUnitService deviceUnitService;
    @Autowired
    private DeviceSwitchSubService deviceSwitchSubService;
    @Transactional
    public void modifyDeviceLocation(DeviceLocation deviceLocation){
        /*查询位置信息*/
        DeviceLocation deviceLocationOld =deviceLocationService.getLocationByDeviceId(deviceLocation.getDeviceId());
        if(deviceLocationOld !=null ){
            deviceLocationService.updateDeviceLocationInvalid(deviceLocationOld.getCabinetId(),deviceLocationOld.getDeviceId());
        }
        int start = deviceLocation.getStartNum();
        int end = deviceLocation.getEndNum();
        for(int i=start;i<=end;i++){
            deviceLocationService.updateDeviceLocationUse(deviceLocation.getCabinetId(),i,deviceLocation.getDeviceId());
        }
        //位置信息更新
        deviceLocationService.updateLocation(deviceLocation);
    }

    @Transactional
    public void modifyDeviceLocation(JSONObject json){
        Long userId = json.getLong("userID");
        if(json.containsKey("device_base")){
            DeviceBase deviceBase = JSON.parseObject(json.getJSONObject("device_base").toJSONString(),DeviceBase.class);
            /*服务器*/
            if(ResConstant.EQPT_TYPE_SERVER.equals(deviceBase.getEqptType())){
                if(json.containsKey("device_server")){
                    DeviceServer deviceServer = JSON.parseObject(json.getJSONObject("device_server").toJSONString(),DeviceServer.class);
                    deviceServer.setUpdateUser(userId);
                    deviceServerService.updateDeviceServer(deviceServer);
                }else {
                    //throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_server 节点信息不存在！");
                }
                if(ResConstant.DEVICE_STATE_ON.equals(deviceBase.getState())){

                    if(json.containsKey("device_ip")){
                        /*删除ip信息*/
                        deviceIpService.deleteDeviceIp(deviceBase.getDeviceId());
                        JSONArray ipList = json.getJSONArray("device_ip");
                        ipList.stream().forEach(o -> {
                            DeviceIp deviceIp = JSON.parseObject(JSON.toJSONString(o),DeviceIp.class);
                            deviceIp.setDeviceId(deviceBase.getDeviceId());
                            deviceIp.setUseTag("1");
                            //插入
                            deviceIpService.insertDeviceIp(deviceIp);
                        });
                    }else{
                        //throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_ip 节点信息不存在！");
                    }
                }else if(ResConstant.DEVICE_STATE_FREE.equals(deviceBase.getState())){

                }else if(ResConstant.DEVICE_STATE_OFF.equals(deviceBase.getState())){

                }
                /*交换机*/
            }else if(ResConstant.EQPT_TYPE_SWITCH.equals(deviceBase.getEqptType())){
                if(json.containsKey("device_switch")){
                    DeviceSwitch deviceSwitch = JSON.parseObject(json.getJSONObject("device_switch").toJSONString(),DeviceSwitch.class);
                    deviceSwitch.setUpdateUser(userId);
                    deviceSwitchService.updateSwitchManage(deviceSwitch);
                }else {
                    //throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_server 节点信息不存在！");
                }
            }else if(ResConstant.EQPT_TYPE_CPE.equals(deviceBase.getEqptType())){

            }

            /*更新设备基础状态*/
            deviceBaseService.updateDeviceBaseState(deviceBase.getDeviceId(),deviceBase.getState());

        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_base 节点信息不存在！");
        }

        if(json.containsKey("device_location")){
            JSONObject location = json.getJSONObject("device_location");
            DeviceLocation deviceLocation = JSON.parseObject(location.toJSONString(),DeviceLocation.class);
            deviceLocation.setUpdateUser(userId);
             /*查询位置信息*/
            DeviceLocation deviceLocationOld =deviceLocationService.getLocationByDeviceId(deviceLocation.getDeviceId());
            if(deviceLocationOld !=null ){
                deviceLocationService.updateDeviceLocationInvalid(deviceLocationOld.getCabinetId(),deviceLocationOld.getDeviceId());
            }
            Integer start = deviceLocation.getStartNum();
            Integer end = deviceLocation.getEndNum();
            if(start != null && end != null){
                for(int i=start;i<=end;i++){
                    deviceLocationService.updateDeviceLocationUse(deviceLocation.getCabinetId(),i,deviceLocation.getDeviceId());
                }
            }
            //位置信息更新
            deviceLocationService.updateLocation(deviceLocation);
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"device_location 节点信息不存在！");
        }


    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Object getLocationList(JSONObject json) {
        Object object = null;

        if(PageHelperUtils.isPage(json)){
            PageHelperUtils.setPageParam(json);
            List<Map<String,Object>> list = deviceLocationService.getDeviceLocationList(json.getString("eqptType"),json.getString("state"));
            PageInfo pageInfo =null;
            if(json.containsKey("deviceId") && !StringUtils.isEmpty(json.getLong("deviceId"))){
                list = list.stream().filter(obj->Long.parseLong(obj.get("deviceId").toString()) == json.getLong("deviceId")).collect(Collectors.toList());
            }
            pageInfo = new PageInfo(JSON.parseArray(JsonUtil.toJson(list)));
            object = JSON.parseObject(JSON.toJSONString(pageInfo, SerializerFeature.WriteMapNullValue));
        }else{
            List<Map<String,Object>> list = deviceLocationService.getDeviceLocationList(json.getString("eqptType"),json.getString("state"));
            if(json.containsKey("deviceId") && !StringUtils.isEmpty(json.getLong("deviceId"))){
                list = list.stream().filter(obj->Long.parseLong(obj.get("deviceId").toString()) == json.getLong("deviceId")).collect(Collectors.toList());
            }
            object = JSON.parseArray(JsonUtil.toJson(list));
        }
        return object;
    }

    public JSONObject getDeviceInfo(Long deviceId){
        JSONObject result = new JSONObject();
        DeviceBase deviceBase = deviceBaseService.getDeviceBaseByDeviceId(deviceId);
        DeviceLocation deviceLocation = deviceLocationService.getLocationByDeviceId(deviceId);
        if(ResConstant.EQPT_TYPE_SERVER.equals(deviceBase.getEqptType())){
            DeviceServer deviceServer = deviceServerService.getDeviceServerByDeviceId(deviceId);
            result.put("device_server",deviceServer);
            if(ResConstant.DEVICE_STATE_ON.equals(deviceBase.getState())){
                List<JSONObject> listIp = deviceIpService.getDeviceIpById(deviceId);
                result.put("device_ip",listIp);
            }else if(ResConstant.DEVICE_STATE_FREE.equals(deviceBase.getState())){

            }else if(ResConstant.DEVICE_STATE_OFF.equals(deviceBase.getState())){

            }
        }else if(ResConstant.EQPT_TYPE_SWITCH.equals(deviceBase.getEqptType())){
            DeviceSwitch deviceSwitch = deviceSwitchService.getDeviceSwitchByDeviceId(deviceId);
            result.put("device_switch",deviceSwitch);

        }else if(ResConstant.EQPT_TYPE_CPE.equals(deviceBase.getEqptType())){

        }
        result.put("device_base",deviceBase);
        result.put("device_location",deviceLocation);
        return result;
    }

    /*设备删除*/
    public void deleteDeviceInfos(Long deviceId){
        /*查询设备基本信息*/
        DeviceBase deviceBase = deviceBaseService.getDeviceBaseByDeviceId(deviceId);
        if(deviceBase != null){
            /*删除机架位置信息*/
            deviceLocationService.deleteLocation(deviceId);
            /*修改设备使用状态*/
            deviceLocationService.updateCabinetUseStateByDevice(deviceId);
            /*删除设备基本信息*/
            deviceBaseService.deleteDeviceBase(deviceId);
            /*删除具体类型的设备信息*/
            if(ResConstant.EQPT_TYPE_SERVER.equals(deviceBase.getEqptType())){
                deviceServerService.deleteDeviceServer(deviceId);
                deviceIpService.deleteDeviceIp(deviceId);
                deviceUnitService.deleteDeviceUnit(deviceId);
            }else if(ResConstant.EQPT_TYPE_SWITCH.equals(deviceBase.getEqptType())){
                deviceSwitchService.deleteDeviceSwitch(deviceId);
                deviceSwitchSubService.deleteSwitchSub(deviceId);
            }
            /*处理具体设备下面的额外信息*/
        }

    }

    /*下线设备*/
    public void shelvesDevice(Long deviceId,String eqptType,Long userId){
        /*位置信息*/
        DeviceLocation location =null;
        location = deviceLocationService.getLocationByDeviceId(deviceId);
        location.setUpdateUser(userId);
        location.setCabinetCode(null);
        location.setCabinetId(null);
        location.setState(ResConstant.DEVICE_LOCATION_ONLINE);
        location.setRoomId(null);
        location.setRoomName(null);
        deviceLocationService.updateLocation(location);

        /*修改设备信息*/
        deviceBaseService.updateDeviceBaseState(deviceId,ResConstant.DEVICE_STATE_OFF);
        /*修改管理信息*/
        if(ResConstant.EQPT_TYPE_SERVER.equals(eqptType)){
            DeviceServer deviceServer = new DeviceServer();
            deviceServer.setDeviceId(deviceId);
            deviceServer.setUpdateUser(userId);
            deviceServerService.updateDeviceServer(deviceServer);
        }else if(ResConstant.EQPT_TYPE_SWITCH.equals(eqptType)){
            DeviceSwitch deviceSwitch = new DeviceSwitch();
            deviceSwitch.setDeviceId(deviceId);
            deviceSwitch.setUpdateUser(userId);
            deviceSwitch.setPurpose(null);
            deviceSwitch.setHostName(null);
            deviceSwitch.setManageIp(null);
            deviceSwitchService.updateSwitchManage(deviceSwitch);
        }
    }

}
